# -*- coding: utf-8 -*-
import json
import openpyxl
import os
import fnmatch
import script_template
import file_operate
import pathcfg
import re
import ast

# 指定要查找的文件类型，用逗号分隔
extension = '*.xlsx'

# 有效类型
validtypes = ["int", "float", "string", "bool",
              "int[]", "int[][]", "string[]", "string[][]", "auto", "auto[]", "auto[][]", 'object']

validtypes2 = ["number", "float", "string", "bool",
              "number[]", "number[][]", "string[]", "string[][]", "any", "any[]", "any[][]", 'object']

default_values = [0, 0, "", 0, [], [], [], [], "", [], [], {}]

classnem_template = "DT{}{}"

table_name_list = []

def build_table(dir_path, extension):
    for root, dirs, files in os.walk(dir_path):
        for file_name in files:
            # 编辑中的文件，跳过
            if file_name[0] == "~":
                continue
            if fnmatch.fnmatch(file_name, extension):
                file_path = os.path.join(root, file_name)
                read_fild_content(file_path)
        script_template.create_table_name_cfg(table_name_list)



# 读取文件内容
def read_fild_content(file_path):
    # 打开Excel文件, data_only: 只读值，否则会读到公式
    workbook = openpyxl.load_workbook(file_path, data_only = True)
    filename, ext = os.path.splitext(os.path.basename(file_path))


    # 选择工作表
    for sheetname in workbook.sheetnames:
        # 遍历行并读取数据
        data = []
        for row in workbook[sheetname].iter_rows():
            row_data = []
            if row[0].value == None: continue
            for cell in row:
                row_data.append(cell.value)
                # if cell.value == None:
                #     row_data.append("")
                # else:
                #     row_data.append(cell.value)
            data.append(row_data)
        # deal_array_to_json(data, sheetname, filename)
        convert_to_jsondata(data, sheetname, filename)
        # break



def convert_to_jsondata(array, sheetname, filename):
    jsondata = {}

    if len(array) <= 0 : return

    field_note_arr = array[0]
    field_name_arr = array[1]
    field_type_arr = array[2]

    jnotearr = []  # 字段注释
    jnamearr = []  # 字段名
    jtypearr = []  # 字段类型
    jtypearrts = []  # 字段类型
    validindexs = []  # 有效字段下标数组
    for index in range(len(field_type_arr)):
        fieldnote = field_note_arr[index] or ""
        fieldname = field_name_arr[index]
        fieldtype = field_type_arr[index]
        # 字段类型合法并且字段名不为空
        if fieldtype and fieldname and len(fieldtype) > 0 and len(fieldname) > 0:
            idx = validtypes.index(fieldtype)
            if idx == -1: continue
            jnotearr.append(fieldnote)
            jnamearr.append(fieldname)
            jtypearr.append(validtypes[idx])
            jtypearrts.append(validtypes2[idx])
            validindexs.append(index)

    classname = classnem_template.format(filename.title(), sheetname.title())
    table_name_list.append(classname)
    print(classname)
    # 类名
    jsondata["classname"] = classname
    # 字段注释
    jsondata["fieldnotes"] = jnotearr
    # 字段名
    jsondata["fieldnames"] = jnamearr
    # 字段类型
    jsondata["fieldtypes"] = jtypearr
    # 字段类型ts语言
    jsondata["fieldtypests"] = jtypearrts
    # 有效字段下标
    jsondata["validindexs"] = validindexs
    # 有效字段下标
    jsondata["classdata"] = convert_to_classdata(array, jsondata)

    #生成cs文件
    script_template.create_table_class(jsondata)

    #生成json文件
    script_template.create_table_json(jsondata)

def convert_to_classdata(array, jsondata):
    # 有效字段下标
    validindexs = jsondata["validindexs"]

    # 字段名
    fieldnames = jsondata["fieldnames"]
    fieldtypes = jsondata["fieldtypes"]

    classdata = []
    for i in range(3, len(array)):
        arr = array[i]
        data = {}
        for index in validindexs:
            idx = validindexs.index(index)
            type = fieldtypes[idx]
            data[fieldnames[idx]] = deal_value(type, arr[index])
        classdata.append(data)
    return classdata

def convert_value(s):
    try:
        return int(s)  # 先尝试转整数
    except ValueError:
        try:
            return float(s)  # 再尝试转浮点数
        except ValueError:
            return s  # 否则保留原字符串

def deal_value(type, value):
    if value :
        if(type == "int[]" or type == "string[]" or type == "auto[]"):
            parts = str(value).split(";")
            return [convert_value(part.strip()) for part in parts if part.strip()]
        elif(type == "int[][]" or type == "string[][]" or type == "auto[][]"):
            rows = str(value).split("|")
            # return [str(row).split(";") for row in rows]
            return [deal_value(type.rsplit("[]", 1)[0], row) for row in rows]
        elif(type == 'object'):
            return parse_dict_string(value)
        return value
    else:
        idx = validtypes.index(type)
        return default_values[idx]

def parse_dict_string(json_str):
    try:
        # 先用ast.literal_eval解析成Python对象
        json_str = re.sub(r'([{,]\s*)([a-zA-Z_]\w*)(\s*:)', r'\1"\2"\3', json_str)
        # parsed = ast.literal_eval(json_str)
        print(json_str)
        # 再转换为标准JSON字符串（可选步骤）
        return json.loads(json_str)
    except (SyntaxError, ValueError, TypeError):
        return json_str  # 解析失败则返回原字符串

# file_operate.clear_all_files(pathcfg.wjson_dir_path)
# file_operate.clear_all_files(pathcfg.wcs_dir_path)
# build_table(pathcfg.rxlsx_dir_path, extension)
